<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\Article;
use app\models\Tool;
use app\models\File;

class ArticleController extends Controller
{
	private $userid;
	private $usertype;

	public function beforeAction($action)
	{
		if(!(isset($_SESSION['cms_userid']) && $_SESSION['cms_userid'] != null))
		{
			return $this->redirect(['admin/login']);
		}
		if ($_SESSION['cms_usertype'] == 1) {
			throw new NotFoundHttpException("没有权限");
			
		}
		$this->userid = $_SESSION['cms_userid'];
		$this->usertype = $_SESSION['cms_usertype'];
		return true;
	}

	public function actionIndex()
	{
		//return json_encode(Article::getAll());
		return $this->render("index",['articles'=>Article::getAll()]);
	}

	public function actionListby(){
		$order = $_GET['order'];
		return $this->render("index",['articles'=>Article::getAllByOrder($order)]);
	}

	public function actionPublished()
	{
		return $this->render("index",['articles'=>Article::getPublished($_SESSION['cms_userid'])]);
	}

	public function actionAuditing()
	{
		return $this->render("index",['articles'=>Article::getAuditing($_SESSION['cms_userid'])]);
	}

	public function actionListbycategory(){
		if(isset($_GET['categoryid'])){
			$categoryid = $_GET['categoryid'];
		}
		else{
			$categoryid = '0';
		}

		return $this->render("index",['articles'=>Article::getAllByCategory($categoryid)]);
	}

	public function actionCreate()
	{
		return $this->render("articlecreate",['category'=>$this->categoryTree(),'group'=>Tool::Group()]);
	}

	//添加文章
	public function actionArticleadd()
	{
		//var_dump($_POST);
		//var_dump($_FILES);die();

		$title 		= $_POST['title'];
		$author 	= $_POST['author'];
		$keyword 	= $_POST['keyword'];
		$abstract 	= $_POST['abstract'];
		$comment 	= $_POST['comment'];
		$template 	= $_POST['template'];
		$audit 		= $_POST['audit'];
		$priority 	= $_POST['priority'];
		$category 	= $_POST['category'];
		$group 		= $_POST['group'];
		$content 	= "";
		if (isset($_POST['content']))
			$content = $_POST['content'];
		$content = str_replace($content, "'", "");

		$rawcontent = $_POST['rawcontent'];
		$rawcontent = str_replace($rawcontent, "'","");

		$posterid = $_SESSION['cms_userid'];//从session获取

		if($audit == '1')
		{
			$updatetime = date("Y-m-d H:i:s");
			$status = 1;

			$sql = "INSERT INTO tbl_article(title,author,posterid,updatetime,priority,keywords,abstract,comment,content,rawcontent,template,status) VALUES('$title','$author','$posterid','$updatetime','$priority','$keyword','$abstract','$comment','$content','$rawcontent','$template','$status')";
		}
		else
		{
			$updatetime = date("Y-m-d H:i:s");
			$submittime = date("Y-m-d H:i:s");
			$publishtime = date("Y-m-d H:i:s");
			$status = 3;

			$sql = "INSERT INTO tbl_article(title,author,posterid,updatetime,submittime,publishtime,priority,keywords,abstract,comment,content,rawcontent,template,status) VALUES('$title','$author','$posterid','$updatetime','$submittime','$publishtime','$priority','$keyword','$abstract','$comment','$content','$rawcontent','$template','$status')";
		}

		$connection = Yii::$app->db;
		$flag = $connection->createCommand($sql)->execute();
		if($flag){
			$id = $connection->createCommand("SELECT last_insert_id() as id")->queryOne();
			$id = $id['id'];

			if($group != "")
			{
				$group = explode(',', $group);
				foreach ($group as $v_group) {
					$connection->createCommand("INSERT INTO tbl_article_group(articleid,groupid) VALUES($id,'$v_group')")->execute();
				}
			}

			if($category != "")
			{
				$category = explode(',', $category);
				foreach ($category as $v_category) {
					$connection->createCommand("INSERT INTO tbl_article_category(articleid,categoryid) VALUES($id,'$v_category')")->execute();
				}

				$categoryNames = "";
				if (empty($category) || (sizeof($category) < 1)){
					$categoryNames = "";
				}else{
					$categoryNames = $this->getCategoryNamesByArticleid($category[0]);
				}

				$sql = "UPDATE tbl_article set category_name = '$categoryNames' where id = $id";
				$connection->createCommand($sql)->execute();
			}

			//保存上传文件
			if(!empty($_FILES))
			{
				foreach ($_FILES as $key => $file) {
					if($file['error'] == 0)
					{
						$customName = '';
						if(isset($_POST[str_replace("file","name" , $key)]))
						{
							$customName = $_POST[str_replace("file","name" , $key)];
						}
						File::saveAttach($id,$file,$customName);

					}
					
				}
			}

			return $this->redirect(['index']);
		}
		else
		{
			throw new NotFoundHttpException("文章添加失败");
			
		}
	}

	/*
	*  提交审核，编辑中状态   1->2
	*/
	public function actionApplyaudit()
	{
		$id = $_POST['id'];
		$cellphone = $_POST['cellphone'];

		$info = Article::getStatus($id);
		if(!($this->usertype == '4' || $this->userid == $info['posterid']))
		{
			return ;
			//throw new NotFoundHttpException("没有权限");
			
		}

		$auditorid = $_POST['auditorid'];

		Article::submitAudit($id,$auditorid,$cellphone);

		//return $this->redirect(['index']);

	}

	/*
	* 撤回 ， 3,2 -> 1
	*/
	public function actionDelaudit()
	{
		$id = $_POST['id'];
		$info = Article::getStatus($id);

		if($this->usertype == '4' || $this->userid == $info['posterid'] || $this->userid == $info['auditorid'])
		{
			Article::changeStatus($id,1);
		}

		
	}

	/*
	* 审核
	*/
	public function actionDoaudit()
	{
		//var_dump($_POST);
		$id = $_POST['id'];

		$info = Article::getStatus($id);
		if($this->userid != $info['auditorid'])
		{
			return ;
			//throw new NotFoundHttpException("没有权限");
			
		}

		$auditresult = $_POST['auditresult'];
		$comment = $_POST['comment'];
		$nextauditor = $_POST['nextauditor'];
		$cellphone = $_POST['cellphone'];

		$auditorid = $_SESSION['cms_userid']; //从session中读取

		Article::doAudit($id,$auditresult,$comment,$nextauditor,$auditorid,$cellphone);

		//return $this->redirect(['index']);
	}

	/*
	* 审核历史
	*/
	public function actionAudithistory()
	{
		$id = $_GET['id'];
		$connection = Yii::$app->db;
		$query = $connection->createCommand("SELECT aa.audittime,aa.status,aa.comment,u.username FROM tbl_article_audit aa LEFT JOIN tbl_user u ON aa.auditorid = u.id WHERE aa.articleid = $id ORDER BY aa.id ASC")->queryAll();
		return json_encode($query);
	}

	//删除文章
	public function actionDelarticle()
	{
		$id = $_POST['id'];
		$info = Article::getStatus($id);
		if($this->usertype == '4' || $this->userid == $info['posterid'] || $this->userid == $info['auditorid'])
		{
			Article::Delete($id);
		}
	
	}

	//修改文章
	public function actionEditarticle()
	{
		$id = $_GET['id'];
		$info = Article::getStatus($id);
		if(!(($this->usertype == '4' || $this->userid == $info['posterid']) && $info['status'] == '1'))
		{
			throw new NotFoundHttpException("没有权限");
			
		}

		return $this->render("editarticle",[
			'article' => Article::getArticleById($id),
			'category'=>$this->categoryTree(),
			'group'=>Tool::Group(),
			'groupselected' => Article::getGroupSelected($id),
			'categoryselected' => Article::getCategorySelected($id),
			'attachment' => Article::getAttachment($id)
		]);
	}

	public function actionArticlemodify()
	{
		//var_dump($_POST);
		$id 		= $_POST['id'];
		$title 		= $_POST['title'];
		$author 	= $_POST['author'];
		$keywords 	= $_POST['keyword'];
		$abstract 	= $_POST['abstract'];
		$comment 	= $_POST['comment'];
		$template 	= $_POST['template'];
		$audit 		= $_POST['audit'];
		$priority 	= $_POST['priority'];
		$category 	= $_POST['category'];
		$group 		= $_POST['group'];
		$content 	= "";
		if (isset($_POST['content']))
			$content = $_POST['content'];
		$content = str_replace("'","",$content);

		$rawcontent = $_POST['rawcontent'];
		$rawcontent = str_replace("'", "",$rawcontent);

	//	$posterid = 1;//从session获取

		if($audit == '1')
		{
			$updatetime = date("Y-m-d H:i:s");
			$status = 1;

			//$sql = "INSERT INTO tbl_article(title,author,posterid,updatetime,priority,keywords,abstract,comment,content,rawcontent,template,status) VALUES('$title','$author','$posterid','$updatetime','$priority','$keyword','$abstract','$comment','$content','$rawcontent','$template','$status')";
			$sql = "UPDATE tbl_article SET title = '$title',author = '$author',updatetime = '$updatetime',priority='$priority',keywords = '$keywords',abstract='$abstract',comment='$comment',content='$content',rawcontent='$rawcontent',template='$template',status = $status WHERE id = $id";
		}
		else
		{
			$updatetime = date("Y-m-d H:i:s");
			$submittime = date("Y-m-d H:i:s");
			$publishtime = date("Y-m-d H:i:s");
			$status = 3;

			//$sql = "INSERT INTO tbl_article(title,author,posterid,updatetime,submittime,publishtime,priority,keywords,abstract,comment,content,rawcontent,template,status) VALUES('$title','$author','$posterid','$updatetime','$submittime','$publishtime','$priority','$keyword','$abstract','$comment','$content','$rawcontent','$template','$status')";
			$sql = "UPDATE tbl_article SET title = '$title',author = '$author',updatetime = '$updatetime',submittime = '$submittime' ,publishtime = '$publishtime' ,priority='$priority',keywords = '$keywords',abstract='$abstract',comment='$comment',content='$content',rawcontent='$rawcontent',template='$template',status = $status WHERE id = $id";
		}

		$connection = Yii::$app->db;
		$flag = $connection->createCommand($sql)->execute();
		if($flag)
		{
			if($group != "")
			{
				$connection->createCommand("DELETE FROM tbl_article_group WHERE articleid = $id")->execute();
				$group = explode(',', $group);
				foreach ($group as $v_group) {
					$connection->createCommand("INSERT INTO tbl_article_group(articleid,groupid) VALUES($id,'$v_group')")->execute();
				}
			}

			if($category != "")
			{
				$connection->createCommand("DELETE FROM tbl_article_category WHERE articleid = $id")->execute();
				$category = explode(',', $category);
				foreach ($category as $v_category) {
					$connection->createCommand("INSERT INTO tbl_article_category(articleid,categoryid) VALUES($id,'$v_category')")->execute();
				}

				$categoryNames = "";
				if (empty($category) || (sizeof($category) < 1)){
					$categoryNames = "";
				}else{
					$categoryNames = $this->getCategoryNamesByArticleid($category[0]);
				}


				$sql = "UPDATE tbl_article set category_name = '$categoryNames' where id = $id";
				$connection->createCommand($sql)->execute();
			}

			if($_POST['attachmentvalue'] != "")
			{
				$attach = json_decode($_POST['attachmentvalue'],true);
				
				foreach ($attach as $avalue) {
					if(trim($avalue["attachvalue"]) != "")
					{
						$connection->createCommand()->update('tbl_attachment',['fileoriginalname'=>trim($avalue['attachvalue'])],'id='.$avalue['attachid'])->execute();
					}
				}
			}

			if(!empty($_FILES))
			{
				foreach ($_FILES as $key => $file) {
					if($file['error'] == 0)
					{
						$customName = '';
						if(isset($_POST[str_replace("file","name" , $key)]))
						{
							$customName = $_POST[str_replace("file","name" , $key)];
						}
						File::saveAttach($id,$file,$customName);
					}
				}
			}

			return $this->redirect(['index']);
		}
		else
		{
			throw new NotFoundHttpException("文章添加失败");
		}
	}

	//删除单个附件
	public function actionDelattach()
	{
		$id = $_POST['id'];
		$connection = Yii::$app->db;

		//删除文件
		File::delAttachment($id);

		$connection->createCommand("DELETE FROM tbl_attachment WHERE id = $id")->execute();
		
	}

	public function actionCategory()
	{
		//return json_encode($this->categoryTree());
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		return $this->render("category",['tree' => $this->categoryTree()]);
	}

	protected function categoryTree()
	{
		$connection = Yii::$app->db;
		$sql = "SELECT * FROM tbl_category WHERE parent = 0 ORDER BY `order` ASC";
		$rootFolderList = $connection->createCommand($sql)->queryAll();

		$arr = array();

		foreach ($rootFolderList as $rootFolderItem) {
			$row = array(
				'id' => $rootFolderItem['id'],
				'name' => $rootFolderItem['name'],
				'depth' => $rootFolderItem['depth'],
				'children' => $this->getChildren($rootFolderItem['id']),
			);
			$arr[] = $row;
		}

		return $arr;
	}

	protected function getChildren($pid)
	{
		$connection = Yii::$app->db;
		$sql = "SELECT * FROM tbl_category WHERE parent = $pid ORDER BY `order` ASC";
		$subCategoryList = $connection->createCommand($sql)->queryAll();

		if(is_array($subCategoryList) && count($subCategoryList) > 0 ){
			$data =  array();

			foreach ($subCategoryList as $subCategoryItem) {
				$row = array(
					'id' => $subCategoryItem['id'],
					'name' => $subCategoryItem['name'],
					'depth' => $subCategoryItem['depth'],
					'children' => $this->getChildren($subCategoryItem['id']),
				);

				$data[] = $row;
			}
			return $data;
		}
		else{
			return null;
		}

	}

	public function actionCatcreate()
	{
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		if(isset($_GET['id'])){
			$id = $_GET['id'];
		}
		else{
			$id = '0';
		}

		return $this->render("categorycreate",['type'=> 'new','category' => ['id'=>$id,'name'=>'','order'=>1]]);
	}

	public function actionCatadd()
	{
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		$name = $_POST['name'];
		$id = $_POST['id'];
		$order = $_POST['order'];

		if (empty($order)){
			$order = 1;
		}

		$connection = Yii::$app->db;
		$sql = "SELECT depth,`order` FROM tbl_category WHERE parent = $id ORDER BY `order` DESC";
		$last = $connection->createCommand($sql)->queryOne();
		
		if($last){
			$sql = "INSERT INTO tbl_category(name,parent,depth,`order`) VALUES('$name',$id,".$last['depth'].",".($order).")";
			
			$connection->createCommand($sql)->execute();
		}
		else
		{
			if($id == 0)
			{
				$depth = 0;
			}
			else
			{
				$parentDepth = $connection->createCommand("SELECT depth FROM tbl_category WHERE id=$id")->queryOne();
				$depth = $parentDepth['depth']+1;
			}
			
			$sql = "INSERT INTO tbl_category(name,parent,depth,`order`) VALUES('$name',$id,$depth,$order)";
			$connection->createCommand($sql)->execute();
		}

		return $this->redirect(['category']);	
	}

	public function actionCatupdate()
	{
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		$id = $_GET['id'];
		$connection = Yii::$app->db;
		$category = $connection->createCommand("SELECT id,name,`order` FROM tbl_category WHERE id=$id")->queryOne();
		return $this->render("categorycreate",['type'=> 'modify','category' => $category]);
	}

	public function actionCatmodify()
	{
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		$id = $_POST['id'];
		$name = $_POST['name'];
		$order = $_POST['order'];

		if (empty($order)){
			$order = 1;
		}

		$connection = Yii::$app->db;
		$connection->createCommand("UPDATE tbl_category SET name='$name', `order` = '$order' WHERE id=$id")->execute();
		return $this->redirect(['category']);
	}

	public function actionDeletecat()
	{
		if($this->usertype == '2')
		{
			throw new NotFoundHttpException("没有权限");
			
		}
		$id = $_POST['id'];
		$connection = Yii::$app->db;
		$connection->createCommand("DELETE FROM tbl_category WHERE id=$id")->execute();
		//删除子类，递归
	}

    public function actionGetauditor()
    {
    	$connection = Yii::$app->db;
    	$query = $connection->createCommand("SELECT id,username FROM tbl_user WHERE usertype=4 OR usertype=3")->queryAll();
    	return json_encode($query);
    }

	private function getCategoryNamesByArticleid($categoryid){
		$result = "";
		if (empty($categoryid))
			return $result;

		$connection = Yii::$app->db;
		$query = $connection->createCommand("SELECT * from tbl_category where id = ".$categoryid)->queryOne();

		if (empty($query)){
			return $result;
		}

		$parentid = $query['parent'];
		$result   = $query['name'];

		while(!empty($parentid)){
			$parentInfo = $connection->createCommand("SELECT * from tbl_category where id = ".$parentid)->queryOne();

			if (empty($parentInfo)){
				return $result;
			}

			$parentid = $parentInfo['parent'];

			$result = $parentInfo['name']."|".$result;
		}

		return $result;

	}
}